import { onBeforeUnmount } from 'vue';

function nextFrame(fn) {
  requestAnimationFrame(() => requestAnimationFrame(fn));
}

/**
 * 简单动画指令
 * @param props
 * @returns
 */
function useTransition(props) {
  const {
    el
  } = props;
  const endTransition = e => {
    if (e.target && el().contains(e.target)) {
      el().classList.remove(props.startClass);
      props.onLeave && props.onLeave();
    }
    el().removeEventListener("transitionend", endTransition);
  };
  const enterEndTransition = e => {
    if (e.target && el().contains(e.target)) {
      props.enterEndClass && el().classList.add(props.enterEndClass);
    }
    props.onEnterEnd && props.onEnterEnd();
    el().removeEventListener("transitionend", enterEndTransition);
  };
  onBeforeUnmount(() => {
    el() && el().removeEventListener("transitionend", endTransition);
    el() && el().removeEventListener("transitionend", enterEndTransition);
  });
  return {
    enter() {
      if (el()) {
        el().classList.add(props.startClass);
        // 确保移除了事件
        el().removeEventListener("transitionend", endTransition);
        el().removeEventListener("transitionend", enterEndTransition);
        nextFrame(() => {
          el().addEventListener("transitionend", enterEndTransition);
          el().classList.add(props.activeClass);
          props.onEnter && props.onEnter();
        });
      }
    },
    leave() {
      if (el()) {
        el().classList.remove(props.activeClass);
        props.enterEndClass && el().classList.remove(props.enterEndClass);
        el().addEventListener("transitionend", endTransition);
      }
    }
  };
}

export { useTransition as default, nextFrame };
